package cn.uncode.session;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;

import cn.uncode.session.data.SessionCacheManager;

public class SessionSharingFilter implements Filter {
	
	public static final String TOKEN_NAME_KEY = "tokenName";
	
	private ServletContext servletContext;

	private String tokenName;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		servletContext = filterConfig.getServletContext();
		tokenName = filterConfig.getInitParameter(TOKEN_NAME_KEY);
		if(StringUtils.isBlank(tokenName)) {
			tokenName = "JSESSIONID";
		}
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest httpServletRequest = (HttpServletRequest)request;
		HttpServletResponse httpServletResponse = (HttpServletResponse)response;
		SessionHttpServletRequestWrapper sessionHttpServletRequestWrapper = new SessionHttpServletRequestWrapper(httpServletRequest, servletContext, tokenName);
        try{
        	chain.doFilter(sessionHttpServletRequestWrapper, httpServletResponse);
		}catch(Exception e){
			e.printStackTrace();
		}
        finally {
			if(!sessionHttpServletRequestWrapper.isRequestedSessionIdValid()){
				newCookie(httpServletResponse);
				HttpSession httpSession = sessionHttpServletRequestWrapper.getSession(false);
				if(httpSession != null){
					SessionCacheManager.getSessionCache().setMaxInactiveInterval(httpSession.getId(), 0);
				}
			}
		}
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
	}

	public String getTokenName() {
		return tokenName;
	}
	
	private void newCookie(HttpServletResponse response) {
		Cookie cookie = new Cookie(tokenName, null);
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}

}
